package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/239103/sshcmd/sshclient"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type Config struct {
	Commands []struct {
		Host     string `json:"host"`
		Port     string `json:"port"`
		Username string `json:"username"`
		Password string `json:"password"`
		Command  string `json:"command"`
	} `json:"commands"`
}

type command struct {
	Host     string
	Port     string
	Username string
	Password string
	Command  string
}

func runCommand(c command) {
	// Dial into remote host
	if client, err := sshclient.SSHDial(c.Host, "22", c.Username, c.Password); err == nil {
		// execute command on remote host
		fmt.Println(sshclient.RunCMD(client, c.Command))
	}
}

func main() {
	// The default configuration file named "config.json" placed in same directory with execution file.
	PthSep := string(os.PathSeparator)
	cmdDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	configFile := cmdDir + PthSep + "config.json"

	fb, err := ioutil.ReadFile(configFile)

	if err != nil {
		log.Fatal(errors.New("Errors occurred while open configuration file: " + configFile))
	}

	var config Config
	err = json.Unmarshal(fb, &config)
	if err != nil {
		log.Fatal(errors.New("Errors occurred while reading configuration file: " + configFile))
	}

	for i := range config.Commands {
		if strings.TrimSpace(config.Commands[i].Host) != "" &&
			strings.TrimSpace(config.Commands[i].Port) != "" &&
			strings.TrimSpace(config.Commands[i].Username) != "" &&
			strings.TrimSpace(config.Commands[i].Password) != "" &&
			strings.TrimSpace(config.Commands[i].Command) != "" {
			var cmd command
			cmd.Host = config.Commands[i].Host
			cmd.Port = config.Commands[i].Port
			cmd.Username = config.Commands[i].Username
			cmd.Password = config.Commands[i].Password
			cmd.Command = config.Commands[i].Command
			runCommand(cmd)
		}
	}
}
